package admission.ecnu.mainservlet;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import admission.ecnu.interfaces.IResponseProcessor;



public class JsonResponseProcessor implements IResponseProcessor {

	public void processContext(RnsContext context) {

			String returnObjectString = null;

			if (context.getJsonResponseObject() instanceof JSONObject) {

				JSONObject returnObject = (JSONObject) context.getJsonResponseObject();

				if (context.getErrorMessage().length() > 0)
					if (returnObject.has("errormessage")) {

						try {
							returnObject.put("errormessage", returnObject
									.getString("errormessage")
									+ " " + context.getErrorMessage());
							
							returnObject.put("issuccess",false);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						try {
							returnObject.put("errormessage", context
									.getErrorMessage());
							
							returnObject.put("issuccess",false);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

				if (returnObject.has("outputasstring")) {
					try {
						if (returnObject.getBoolean("outputasstring"))
							if (returnObject.has("output"))
								returnObjectString = returnObject.get("output").toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else{
					try{
						returnObjectString = returnObject.toString();
					}catch(Exception e){
						returnObjectString = "{issuccess:false,isauthorized:false,errormessage:'未授权的操作'}";
					}
				}
			} else {
				if(context.getJsonResponseObject()!=null)
					returnObjectString = context.getJsonResponseObject().toString();					
			}
			
			if(context.getJsonResponseObject()==null)
				returnObjectString = "{issuccess:false,errormessage:\""+context.getErrorMessage()+"\"}";
				
			try {
				//if(context.getReturnObject()!=null)
					context.getResponse().getWriter().print(returnObjectString);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}
